'''
    静安保安积分商城   jaba=xxx@xxxx
'''

import datetime
import json
import os
import pprint
import random
import time
import requests
import hashlib


def get_nonce():
    """
        生成一个指定长度的随机字符串
        """
    randomlength = 16
    random_str = ''
    base_str = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
    length = len(base_str) - 1
    for i in range(randomlength):
        random_str += base_str[random.randint(0, length)]
    # print(random_str)
    return random_str


def genHeader(data):
    return {
        'Authori-zation': f'Bearer {data}',
        'Form-type': 'routine',
        'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 15_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/8.0.29(0x18001d38) NetType/WIFI Language/zh_CN',
        'Content-Type': 'application/json'
    }

def integral(data, header, index):
    try:
        print(f'第{index}个账号 开始获取积分')
        url = f'https://abjfapi.yuanchixinxi.com/api/sign/user'
        response = requests.post(url=url, headers=header, data=json.dumps({"sign":1,"integral":1,"all":1})).json()
        result = response["data"]
        integral = result['integral']
        today_integral = result['today_integral']
        print(f'第{index}个账号 开始获取积分: 总积分[{integral}]，今日新增积分[{today_integral}]')
        return f'第{index}个账号 开始获取积分: 总积分[{integral}]，今日新增积分[{today_integral}]'
    except Exception as e:
        return f'第{index}个账号 签到异常 {e}'


def signIn(data, header, index):
    try:
        print(f'第{index}个账号 开始签到')
        url = f'https://abjfapi.yuanchixinxi.com/api/sign/integral'
        response = requests.post(url=url, headers=header, data=json.dumps({})).json()
        return f'第{index}个账号 签到返回: {response["data"]["msg"]}'
    except Exception as e:
        return f'第{index}个账号 签到异常 {e}'


'''
抽奖
'''


def lottery(data, header, index):
    try:
        print(f'第{index}个账号 开始抽奖')
        url = f'https://abjfapi.yuanchixinxi.com/api/v2/lottery'
        response = requests.post(url=url, headers=header, data=json.dumps({"id": 2, "type": "1"})).json()
        print(f'第{index}个账号 抽奖返回: {response}')
        return f'第{index}个账号 抽奖返回: {response["data"]["prompt"]}'
    except Exception as e:
        return f'第{index}个账号 抽奖异常 {e}'


'''
阅读
'''


def read(data, header, index):
    try:
        print(f'第{index}个账号 开始阅读')
        url = f'https://abjfapi.yuanchixinxi.com/api/article/details/23'
        response = requests.get(url=url, headers=header).json()
        print(f'第{index}个账号 阅读返回: {response["msg"]}')
        return ''
    except Exception as e:
        return f'第{index}个账号 阅读异常 {e}'


'''
分享
'''


def share(data, header, index):
    try:
        print(f'第{index}个账号 开始分享')
        print(f'第{index}个账号 开始获取商品列表')
        url = f'https://abjfapi.yuanchixinxi.com/api/store_integral/list?store_name&priceOrder=asc&salesOrder&page=1&limit=20&cid=104'
        response = requests.get(url=url, headers=header).json()
        list = random.sample(response["data"], 5)
        for n, item in enumerate(list):
            url = f'https://abjfapi.yuanchixinxi.com/api/user/share?product_id={item["id"]}'
            response = requests.post(url=url, headers=header, data=json.dumps({})).json()
            print(f'第{index}个账号 第{n}次分享返回: {response}')
            sleepmoment(10)

        print(f'第{index}个账号 分享返回: {response}')
        return ''
    except Exception as e:
        return f'第{index}个账号 分享异常 {e}'


'''
答题
'''


def question(data, header, index):
    try:
        print(f'第{index}个账号 开始答题')
        url = f'https://abjfapi.yuanchixinxi.com/api/question/list'
        response = requests.get(url=url, headers=header).json()
        data = response["data"]
        eid = data["e_id"]
        list = data["list"]
        answer_list = []
        for item in list:
            answer = {"question_id": item["id"], "answer": item["answer"]}
            answer_list.append(answer)
            sleepmoment(10)

        answer_data = {"e_id": eid, "list": answer_list}
        url = 'https://abjfapi.yuanchixinxi.com/api/question/submit'
        response = requests.post(url=url, headers=header, data=json.dumps(answer_data)).json()
        print(f'第{index}个账号 答题返回: {response}')
        return ''
    except Exception as e:
        return f'第{index}个账号 答题异常 {e}'


def webhook(message, webhookToken):
    url = f'https://www.pushplus.plus/send'
    headers = {
        'Content-Type': 'application/json'
    }
    data = {
        "token": webhookToken,
        "title": "静安保安",
        "content": message,
        "template": "json"
    }
    response = requests.post(url=url, data=json.dumps(data), headers=headers).json()
    print(f"推送成功")


def genEnvs():
    cks = os.environ['jaba']
    cks = cks.split('@')
    tokenArr = []
    for ck in cks:
        tokenArr.append(ck)
    return tokenArr


def sleepmoment(num):
    random_seconds = random.randint(1, num)
    print(f'休眠{random_seconds}秒')
    time.sleep(random_seconds)


if __name__ == '__main__':
    print('开始执行...')
    sleepmoment(20)
    tokenArray = genEnvs()
    length = len(tokenArray)
    print(f'读取到{length}个账号')
    webhookToken = os.environ['PUSH_PLUS_TOKEN']
    msg = ""
    for index, ck in enumerate(tokenArray):
        header = genHeader(ck)
        msg += signIn(ck,  header, index + 1)
        sleepmoment(10)
        msg += lottery(ck, header, index + 1)
        sleepmoment(10)
        msg += question(ck, header, index + 1)
        sleepmoment(10)
        msg += read(ck, header, index + 1)
        sleepmoment(10)
        msg += share(ck, header, index + 1)
        sleepmoment(10)
        msg += integral(ck,  header, index + 1)
        sleepmoment(10)
    webhook(msg, webhookToken)
